import { useState, useRef, useEffect } from "react";
type IProps = {
  attrData: any;
  data: any[];
  attrKey: string;
  setAttrKey: (...args) => void;
  flag?: boolean;
  title?: boolean;
};
export default function SelectMember(props: IProps) {
  const [selectData, setSelectData] = useState([]);
  const [isFlag, setIsFlag] = useState(false);
  const [containerDirection, setContainerDirection] = useState("");
  const selectRef = useRef<HTMLDivElement>();
  // 处理选中用户
  function HandleSelectMemberClick(item, index) {
    const source = selectData.findIndex(
      (itemx) => itemx.user_name == item.user_name
    );
    let ids = "";
    if (source == -1) {
      selectData.push(item);
      ids = selectData.map((item) => item.user_name).join(",");
      setSelectData([...selectData]);
    } else {
      selectData.splice(source, 1);
      ids = selectData.map((item) => item.user_name).join(",");
      setSelectData([...selectData]);
    }
    props.setAttrKey({
      ...props.attrData,
      Edit: true,
      [props.attrKey]: ids,
    });
  }
  // 返回审核的人员信息
  function returnAuditsInfo(item) {
    if (props.attrKey != "Notify") {
      if (props.attrData.Signature?.includes(item.user_name)) {
        return (
          <div
            className={`h-5 w-12 -left-1 top-1 -rotate-45  absolute border-green-600 border-b-4 border-l-4`}
          ></div>
        );
      } else if (props.attrData.Rejection?.includes(item.user_name)) {
        return (
          <div className=" absolute">
            <div className="py-5 absolute left-[18px] rotate-45 border-red-600 border-l-4"></div>
            <div className="py-5 absolute left-[18px] -rotate-45 border-red-600 border-l-4"></div>
          </div>
        );
      }
    } else {
      return "bg-white";
    }
  }
  useEffect(() => {
    const arr = [];
    // 分割判断的ID
    props.attrData[props.attrKey]?.split(",").forEach((itemx) => {
      const s = props.data.find((itemy) => itemx == itemy.user_name);
      s && arr.push(s);
    });
    arr.length && setSelectData(arr);
  }, [props.attrData]);
  useEffect(() => {
    // 判断是否能往下展开
    if (window.innerHeight - selectRef.current.offsetTop < 330) {
      setContainerDirection("bottom-16");
    } else {
      setContainerDirection("top-16");
    }
    // 点击自己外面的容器关闭自身
    function HandleElementClick(event) {
      if (!selectRef.current?.contains(event.target) && isFlag)
        setIsFlag(false);
    }
    document.addEventListener("click", HandleElementClick);
    return () => {
      document.removeEventListener("click", HandleElementClick);
    };
  }, [selectData, isFlag, props.attrData, window.innerHeight]);
  return (
    <div
      className="relative"
      ref={selectRef}
      onClick={() => props.flag && setIsFlag(true)}
    >
      <div className={`max-w-full`}>
        {/* 选择了抄送人 */}
        <ul className="flex overflow-auto">
          {selectData.map((item) => {
            return (
              <li
                className={`mr-1 pt-1 border w-18 text-center `}
                key={item.id}
              >
                <div className="w-10 h-10 relative mx-auto">
                  {props.attrKey != "Notify" && returnAuditsInfo(item)}
                  <img className="w-full" src={item.avatar} alt="" />
                </div>
                <div className="w-16 font-bold scale-75 border-t">
                  {item.user_name}
                </div>
              </li>
            );
          })}
        </ul>
        {/* 没有选择抄送人 */}
        {selectData.length == 0 && (
          <div className="border w-16 text-center">
            <div className="text-sm scale-75 border-t">选择抄送</div>
          </div>
        )}
      </div>
      <ul
        style={{
          height: isFlag ? "250px" : "0px",
          border: isFlag ? "1px solid #f1efef" : "none",
        }}
        className={`bg-white w-40 line rounded absolute translate-x-1/2 z-50 shadow-2xl transition-all overflow-y-auto
 ${containerDirection}
          `}
      >
        {isFlag &&
          props.data.map((item, index) => {
            return (
              <li
                onClick={() => HandleSelectMemberClick(item, index)}
                className="hover:bg-gray-200  relative w-full shadow cursor-pointer py-1 px-2 flex items-center text-center"
                key={item.id}
              >
                <img
                  className="w-12 h-12 rounded"
                  src={item.avatar}
                  alt={item.nick_name}
                />
                <div className=" flex-1" title={item.nick_name}>
                  <div className="my-o-text-1 scale-90">{item.nick_name}</div>
                  <div className="absolute font-bold scale-75 bottom-0 right-2 truncate">
                    {item.user_name}
                  </div>
                </div>
              </li>
            );
          })}
      </ul>
    </div>
  );
}
